<template>
  <div class="mobile-use-car" @click="hideCarOptions">
    <div class="mobile-header">
      <div class="title">
        <div class="back" @click="goBack">
          <i class="el-icon-arrow-left"></i>
        </div>
        <h2>用车登记</h2>
      </div>
    </div>

    <!-- 添加居中提示 -->
    <div class="tip-message" v-if="showTip">
      <div class="tip-content">
        <i class="el-icon-warning-outline"></i> 车牌号必须从列表中选择
      </div>
    </div>

    <div class="mobile-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="use-car-form">
        <el-form-item label="车牌号" prop="licensePlate">
          <div class="license-plate-selector" @click.stop>
            <el-input 
              v-model="form.licensePlate" 
              placeholder="请输入车牌号" 
              @input="handleLicensePlateInput"
              @focus="onFocus"
            />
            <div class="car-options" v-show="showCarOptions">
              <ul v-if="filteredCarOptions.length > 0">
                <li 
                  v-for="(option, index) in filteredCarOptions" 
                  :key="index" 
                  @click="selectCar(option)"
                >
                  {{ option.licensePlate }} ({{ option.name }})
                </li>
              </ul>
              <div v-else class="no-result">没有匹配的车牌号</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="使用时间" prop="startDt">
          <el-date-picker
            clearable
            v-model="form.startDt"
            type="datetime"
            class="mobile-date-picker mobile-time-fix"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择使用时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="目的地" prop="destination">
          <el-input v-model="form.destination" placeholder="请输入目的地" />
        </el-form-item>
        <el-form-item label="使用人电话" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入使用人电话" readonly />
        </el-form-item>
        <el-form-item label="使用人姓名" prop="userNickName">
          <el-input v-model="form.userNickName" placeholder="请输入使用人姓名" readonly />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" style="width: 100%;">提 交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { addLifeCarUsageRecord } from "@/api/mes/life/lifeCarUsageRecord";
import { getUserProfile } from "@/api/system/user";
import { listLifeCarConfig } from "@/api/mes/life/lifeCarConfig";
import { mapGetters } from 'vuex';

export default {
  name: "MobileUseCar",
  data() {
    return {
      // 表单参数
      form: {
        licensePlate: "",
        startDt: (() => {
          // 获取当前时间戳
          const now = new Date();
          // 根据当前时区与UTC的时差，计算UTC时间
          const utcTime = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
          // 加上8小时得到北京时间（UTC+8）
          const beijingTime = new Date(utcTime.getTime() + 8 * 3600000);
          
          // 格式化为 yyyy-MM-dd HH:mm:ss
          const year = beijingTime.getFullYear();
          const month = String(beijingTime.getMonth() + 1).padStart(2, '0');
          const day = String(beijingTime.getDate()).padStart(2, '0');
          const hours = String(beijingTime.getHours()).padStart(2, '0');
          const minutes = String(beijingTime.getMinutes()).padStart(2, '0');
          const seconds = String(beijingTime.getSeconds()).padStart(2, '0');
          
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        })(),
        destination: "",
        userName: "",
        userNickName: "",
        remark: ""
      },
      // 表单校验
      rules: {
        licensePlate: [
          { required: true, message: "车牌号不能为空", trigger: "manual" }
        ],
        startDt: [
          { required: true, message: "使用时间不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "使用人电话不能为空", trigger: "blur" }
        ],
        userNickName: [
          { required: true, message: "使用人姓名不能为空", trigger: "blur" }
        ],
        destination: [
          { required: true, message: "目的地不能为空", trigger: "blur" }
        ]
      },
      // 车辆配置列表
      carList: [],
      // 过滤后的车辆选项
      filteredCarOptions: [],
      // 是否显示车辆选项
      showCarOptions: false,
      // 是否显示提示
      showTip: false,
      // 输入防抖计时器
      inputTimer: null,
      // 提示消失计时器
      tipTimer: null
    };
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    // 获取URL中的车牌号参数
    const licensePlate = this.$route.query.licensePlate;
    if (licensePlate) {
      this.form.licensePlate = licensePlate;
      // 在组件挂载后清除验证错误
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate('licensePlate');
        }
      });
    }
    
    // 获取当前用户信息
    this.getUserInfo();
    
    // 获取车辆列表
    this.getCarList();
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      getUserProfile().then(res => {
        const userInfo = res.data;
        this.form.userName = userInfo.phonenumber || userInfo.userName;
        this.form.userNickName = userInfo.nickName;
      });
    },
    // 获取车辆列表
    getCarList() {
      // 只获取状态为空闲(0)的车辆
      listLifeCarConfig({ status: 0 }).then(res => {
        this.carList = res.rows || [];
        // 初始加载时，将所有车辆添加到过滤结果中
        this.filteredCarOptions = [...this.carList];
      });
    },
    // 处理车牌号输入
    handleLicensePlateInput() {
      // 在输入时清除该字段的验证错误
      this.$refs.form.clearValidate('licensePlate');
      
      // 隐藏提示
      this.hideTipMessage();
      
      // 过滤车辆选项
      const input = this.form.licensePlate.toLowerCase();
      if (!input) {
        // 如果输入为空，显示所有车辆
        this.filteredCarOptions = [...this.carList];
      } else {
        this.filteredCarOptions = this.carList.filter(car => 
          car.licensePlate.toLowerCase().includes(input)
        );
      }
      // 确保显示下拉列表
      this.showCarOptions = true;
    },
    // 显示提示消息
    showTipMessage() {
      // 取消之前的定时器
      clearTimeout(this.tipTimer);
      
      // 显示提示
      this.showTip = true;
      
      // 设置3秒后自动隐藏
      this.tipTimer = setTimeout(() => {
        this.showTip = false;
      }, 3000);
    },
    // 隐藏提示消息
    hideTipMessage() {
      clearTimeout(this.tipTimer);
      this.showTip = false;
    },
    // 选择车辆
    selectCar(car) {
      this.form.licensePlate = car.licensePlate;
      this.showCarOptions = false;
      
      // 选择有效车牌号后清除验证错误
      this.$refs.form.clearValidate('licensePlate');
      this.hideTipMessage();
    },
    // 隐藏车辆选项
    hideCarOptions() {
      this.showCarOptions = false;
    },
    // 提交表单
    submitForm() {
      // 手动触发表单验证（包括车牌号必填的验证）
      this.$refs["form"].validate(valid => {
        // 如果表单验证不通过，直接返回
        if (!valid) {
          return;
        }
        
        // 如果车牌号为空，不需要额外验证直接返回（表单验证已处理必填项）
        if (!this.form.licensePlate) {
          return;
        }
        
        // 验证车牌号是否有效（在车辆列表中）
        const isLicensePlateValid = this.carList.some(car => 
          car.licensePlate.toLowerCase() === this.form.licensePlate.toLowerCase()
        );
        
        if (!isLicensePlateValid) {
          // 清空车牌号值
          this.form.licensePlate = "";
          
          // 显示提示消息
          this.showTipMessage();
          
          // 重新显示所有车辆选项
          this.filteredCarOptions = [...this.carList];
          
          return;
        }
        
        // 所有验证通过，提交表单
        addLifeCarUsageRecord(this.form).then(response => {
          this.$message({
            message: "用车登记成功:" + response.msg,
            type: "success"
          });
          // 返回首页
          this.goBack();
        });
      });
    },
    // 返回首页
    goBack() {
      this.$router.push("/mobile");
    },
    // 输入框获得焦点时的处理
    onFocus() {
      // 显示下拉列表
      if (this.form.licensePlate) {
        // 如果有输入内容，根据内容过滤
        this.filteredCarOptions = this.carList.filter(car => 
          car.licensePlate.toLowerCase().includes(this.form.licensePlate.toLowerCase())
        );
      } else {
        // 如果没有输入内容，显示所有车辆
        this.filteredCarOptions = [...this.carList];
      }
      
      this.showCarOptions = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.mobile-use-car {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;

  .mobile-header {
    background-color: #409EFF;
    color: white;
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);

    .title {
      display: flex;
      align-items: center;
      width: 100%;
      
      .back {
        margin-right: 10px;
        font-size: 20px;
        cursor: pointer;
      }
      
      h2 {
        margin: 0;
        font-size: 18px;
        flex: 1;
        text-align: center;
      }
    }
  }
  
  // 添加提示样式
  .tip-message {
    position: fixed;
    top: 60px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    z-index: 2000;
    
    .tip-content {
      background-color: rgba(253, 227, 207, 0.95);
      color: #e6a23c;
      padding: 10px 20px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      
      i {
        margin-right: 8px;
        font-size: 18px;
      }
    }
  }

  .mobile-content {
    flex: 1;
    padding: 20px;

    .use-car-form {
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      .el-input, .el-date-picker {
        width: 100%;
      }

      .el-button {
        margin-top: 10px;
      }
      
      .license-plate-selector {
        position: relative;
        width: 100%;
        
        .car-options {
          position: absolute;
          width: 100%;
          max-height: 200px;
          overflow-y: auto;
          background-color: #fff;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          z-index: 10;
          margin-top: 5px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          
          ul {
            list-style: none;
            padding: 0;
            margin: 0;
            
            li {
              padding: 8px 15px;
              cursor: pointer;
              
              &:hover {
                background-color: #f5f7fa;
              }
            }
          }
          
          .no-result {
            padding: 10px 15px;
            color: #909399;
            text-align: center;
            font-size: 14px;
          }
        }
      }
    }

    // 移动端日期选择器样式优化
    >>> .mobile-date-picker {
      width: 100%;
    }

    >>> .el-time-panel__content {
      position: relative;
      overflow: hidden;
    }
    
    >>> .el-time-panel__content::after,
    >>> .el-time-panel__content::before {
      content: "";
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 32px;
      z-index: -1;
      border-top: 1px solid transparent;
      border-bottom: 1px solid transparent;
      margin-top: -16px;
      box-sizing: border-box;
      pointer-events: none;
    }
    
    >>> .el-time-spinner__wrapper {
      overflow: hidden;
      position: relative;
      touch-action: manipulation;
    }
    
    >>> .el-time-spinner__list {
      padding: 0;
      margin: 0;
      list-style: none;
      touch-action: manipulation;
    }
    
    >>> .el-time-spinner__item {
      height: 32px;
      line-height: 32px;
      padding: 0;
      text-align: center;
      cursor: pointer;
      position: relative;
      z-index: 1;
    }
    
    >>> .el-time-spinner__item:hover:not(.disabled):not(.active) {
      background: #f5f7fa;
    }
    
    >>> .el-time-spinner__item.active:not(.disabled) {
      color: #fff;
      background-color: #409EFF;
      font-weight: bold;
      height: 32px;
    }
    
    >>> .el-time-spinner__item.active:not(.disabled)::before {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      height: 100%;
      background-color: rgba(64, 158, 255, 0.1);
      z-index: -1;
    }
    
    >>> .el-time-spinner__list::after {
      content: '';
      display: block;
      width: 100%;
      height: 32px;
      position: absolute;
      top: 50%;
      margin-top: -16px;
      left: 0;
      pointer-events: none;
      visibility: hidden;
    }
    
    >>> .el-time-spinner__list .el-time-spinner__item {
      transform: translateY(0);
      transition: none;
    }
    
    // 移动触屏设备适配
    @media (pointer: coarse) {
      >>> .el-time-spinner__item {
        padding: 8px 0;
        height: 40px;
        line-height: 24px;
      }
      
      >>> .el-time-panel__content::after,
      >>> .el-time-panel__content::before {
        height: 40px;
        margin-top: -20px;
      }
      
      >>> .el-time-spinner__item.active:not(.disabled) {
        height: 40px;
      }
      
      >>> .el-time-spinner__list::after {
        height: 40px;
        margin-top: -20px;
      }
      
      >>> .el-time-panel__footer {
        padding: 12px 5px;
      }
    }
    
    // 全局修复时间选择器
    >>> body .el-time-panel, >>> body .el-picker-panel {
      .el-time-spinner__item {
        height: 40px; 
        line-height: 40px;
        font-size: 16px;
        position: relative;
        z-index: 1;
      }
      
      .el-time-panel__content::after,
      .el-time-panel__content::before {
        content: '';
        position: absolute;
        z-index: 0;
        left: 0;
        right: 0;
        top: 50%;
        height: 40px;
        margin-top: -20px;
        border-top: 1px solid transparent;
        border-bottom: 1px solid transparent;
        box-sizing: border-box;
        pointer-events: none;
      }
    }
  }
}
</style> 